# !/usr/bin/python3
# -- coding: utf-8 --
# -------------------------------
# @Author : 123
# cron "*/10 9-20 * * *" script-path=xxx.py,tag=匹配cron用
# const $ = new Env('掌游币兑换')

import json
import os

import requests
import re

if os.path.isfile('notify.py'):
    from notify import send

    print("加载通知服务成功！")
else:
    print("加载通知服务失败!")


APP_NAME = "掌游币兑换"

# 账号CK信息
ck =  os.environ.get("ZY_CK")

if not ck:
    raise Exception("请配置环境变量:ZY_CK")

# ua信息
ua = "Mozilla/5.0 (Linux; U; Android 14; zh-CN; M2102K1AC Build/UKQ1.231207.002) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/100.0.4896.58 UWS/5.12.4.0 Mobile Safari/537.36 AliApp(DingTalk/7.6.17) com.alibaba.android.rimet/40144870 Channel/700159 language/zh-CN abi/64 xpn/xiaomi UT4Aplus/0.2.25 colorScheme/light"


def token():
    url = "https://app21806.eapps.dingtalkcloud.com/wx/topic/list?from=ding&corp_id=dingba3e73b439e39ce6&shop_id=1"
    headers = {
        "Cookie": ck,
        "Referer": "https://app21806.eapps.dingtalkcloud.com/web/",
        "User-Agent": ua
    }
    r = requests.get(url=url, headers=headers)
    if r.status_code == 200:
        m = re.findall("'X-CSRF-TOKEN': '(.*?)'", r.text)
        if m and len(m) > 0:
            return r.cookies, m[0]


def buy():
    result = token()
    if not result:
        print("获取Token失败")
        return

    r_ck, t = result
    print("获取Token成功:" + t)

    new_ck = ck + f'; laravel_session={r_ck["laravel_session"]}; XSRF-TOKEN={r_ck["XSRF-TOKEN"]}'

    url = 'https://app21806.eapps.dingtalkcloud.com/wx/goods/batchorder'

    headers = {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Cookie": new_ck,
        "User-Agent": ua,
        "Referer": "https://app21806.eapps.dingtalkcloud.com/wx/cart/split",
        "X-CSRF-TOKEN": t
    }

    data = {
        "address_id":	30,
        "carts":	json.dumps([{"sku_id": "393751", "count": "1", "user_message": ""}, {"sku_id": "395149", "count": "1", "user_message": ""}]),
        "receivingTime":	[],
        "coin_type":	1,
        "is_new_order_group":	0,
        "join_order_group_id":	0
    }

    r = requests.post(url=url, headers=headers, data=data)
    if r.status_code == 200:
        return r.text

try:
    r = buy()

    if not r:
        send(APP_NAME, "登录信息失效")
    else:
        j = json.loads(r)
        print(j)
        if "成功" in j["message"]:
            send(APP_NAME, str(r))
        elif j["status_code"] != 404007:
            send(APP_NAME, str(r))
except Exception as e:
    send(APP_NAME, str(e))
    raise e

